﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Configuration;
using System.Text.RegularExpressions;

namespace NetLogger
{
	/// <summary>
	/// Interaction logic for SelectNet.xaml
	/// </summary>
	public partial class SelectNet : Window
	{
		public SelectNet( IEnumerable<NetExistingActivation> nets )
		{
			LoggerId = Properties.Settings.Default.LoggerId;
			Nets = nets;
			NetTypes = ConfigurationManager.AppSettings[ "NetTypes" ].Split( ',' );
			NetName = DateTimeOffset.Now.ToString();
			IsDelayedActivation = false;
			SelectedNet = Nets.FirstOrDefault();
			SelectedNetType = NetTypes.FirstOrDefault();

			DataContext = this;

			InitializeComponent();
		}

		public string LoggerId
		{
			get;
			set;
		}

		public IEnumerable<string> NetTypes
		{
			get;
			private set;
		}

		public string SelectedNetType
		{
			get;
			set;
		}

		public string NetName
		{
			get;
			set;
		}

		public bool? IsDelayedActivation
		{
			get;
			set;
		}

		public IEnumerable<NetExistingActivation> Nets
		{
			get;
			private set;
		}

		public NetExistingActivation SelectedNet
		{
			get;
			set;
		}

		public string CompleteNetName
		{
			get
			{
				return string.Format( "{0} {1} {2}", ConfigurationManager.AppSettings[ "NetTypesPrefix" ],
					SelectedNetType, NetName );
			}
		}

		public bool IsNewEnabled
		{
			get
			{
				return !string.IsNullOrEmpty( SelectedNetType ) && !string.IsNullOrEmpty( NetName );
			}
		}

		public bool IsJoinEnabled
		{
			get
			{
				return SelectedNet != null;
			}
		}

		public bool IsNewNet
		{
			get;
			private set;
		}

		private void OnNew( object sender, RoutedEventArgs e )
		{
			if ( Regex.IsMatch( LoggerId, NetActivation.CallsignRegEx ) )
			{
				if ( LoggerId != Properties.Settings.Default.LoggerId )
				{
					Properties.Settings.Default.LoggerId = LoggerId;
					Properties.Settings.Default.Save();
				}
				DialogResult = true;
				IsNewNet = true;
				Close();
			}
		}

		private void OnJoin( object sender, RoutedEventArgs e )
		{
			if ( Regex.IsMatch( LoggerId, NetActivation.CallsignRegEx ) )
			{
				if ( LoggerId != Properties.Settings.Default.LoggerId )
				{
					Properties.Settings.Default.LoggerId = LoggerId;
					Properties.Settings.Default.Save();
				}
				DialogResult = true;
				Close();
			}
		}
	}
}
